package model

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
	"math"
)

type Goods struct {
	Id     int64
	Name   string
	Price  float64
	TypeId int64
	Status string
	Img    string
	Desc   string
	Num    int64
}

var o orm.Ormer

func init() {
	orm.RegisterDriver("default", orm.DRMySQL)
	orm.RegisterDataBase("default", "mysql", "root:root@tcp(127.0.0.1:3306)/2106a")
	orm.RegisterModel(new(Goods))
	orm.RunSyncdb("default", false, true)
	orm.Debug = true
	o = orm.NewOrm()
}

func Insert(g *Goods) error {
	_, err := o.Insert(g)
	return err
}

func FenYe(page int64, name string) (int64, int64, int64, int64, []byte) {

	searchName := ""
	if name != "" {
		searchName = "%" + name + "%"
	}
	logs.Info(searchName)
	//当前页
	var nowPage int64
	if page != 0 {
		nowPage = page
	}
	fmt.Println(nowPage)
	//总数据
	var g []Goods
	//查数据  All 返回值 一个整型 一个错
	sums, _ := o.QueryTable("goods").Filter("name__contains", name).All(&g)
	fmt.Println(sums)

	//每页显示多少条数据
	showPage := 5
	fmt.Println(showPage)
	//总页数
	cuntPage := math.Ceil(float64(sums) / float64(int64(showPage)))
	fmt.Println(cuntPage)
	//偏移量
	offset := (nowPage - 1) * int64(showPage)
	fmt.Println(offset)
	o.QueryTable("goods").Offset(offset).Limit(showPage).Filter("name__contains", name).All(&g)
	fmt.Println(g)
	jsG, _ := json.Marshal(g)
	return sums, int64(showPage), nowPage, int64(cuntPage), jsG
}

func Delete(id int64) error {
	g := Goods{
		Id: id,
	}
	err := o.Read(&g, "id")
	if err != nil {
		return errors.New("id 不存在")
	}
	_, err = o.Delete(&g, "id")
	if err != nil {
		return err
	}
	return nil
}

func Update(id int64) error {
	g := Goods{
		Id: id,
	}
	err := o.Read(&g, "id")
	if err != nil {
		return errors.New("id 不存在")
	}
	_, err = o.Update(&g)
	if err != nil {
		return err
	}
	return nil
}

func Desc(id int64) (Goods, error) {
	g := Goods{
		Id: id,
	}
	err := o.Read(&g, "id")
	if err != nil {
		return Goods{}, err
	}
	return g, nil
}
